package cn.ydw.community.controller;

import cn.ydw.community.entity.User;
import cn.ydw.community.service.UserService;
import cn.ydw.community.util.CommonUtils;
import cn.ydw.community.util.CommunityConstant;
import cn.ydw.community.util.RedisKeyUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Controller
@Slf4j
public class LoginController implements CommunityConstant {

    @Autowired
    private UserService userService;

    @Autowired
    private Producer producer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String register(){
        return "/site/register";
    }

    @GetMapping("/login")
    public String toLogin(){
        return "/site/login";
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String registerWith(User user, Model model){
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()){
            model.addAttribute("msg", "注册成功,我们已经向您的邮箱发送了一封激活邮件,请尽快激活!");
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        }else{
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            model.addAttribute("typeMsg", map.get("typeMsg"));
            return "/site/register";
        }
    }

    @RequestMapping("/activecode/{userid}/{code}")
    public String activation(@PathVariable("userid")Integer id, @PathVariable("code")String code,Model model){
        int result = userService.activation(id, code);
        if (result == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功,您的账号已经可以正常使用了!");
            model.addAttribute("target", "/login");
        } else if (result == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效操作,该账号已经激活过了!");
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败,您提供的激活码不正确!");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }

    /**
     * 验证码生成
     */
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response) throws IOException {
        //生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);

        //验证码归属
        String kaptchaOwner = CommonUtils.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);  //60秒后cookie到期
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        //验证码存入redis
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(kaptchaKey, text, 60, TimeUnit.SECONDS); // redis存放cookie60秒
        // 将图片输出给浏览器
        response.setContentType("image/png");

        try {
            ServletOutputStream os = response.getOutputStream();

            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            log.error("响应图片验证码失败:" + e.getMessage());
        }

    }

    @PostMapping("/login")
    public String login(String code, String username, String password, boolean rememberme,
                        Model model,/* HttpSession session,*/ HttpServletResponse response, @CookieValue("kaptchaOwner")String kaptchaOwner){
        // 检查验证码
//        String kaptcha = (String) session.getAttribute("kaptcha");
        // 验证图片验证码
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)){
            String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg", "验证码不正确");
            return "/site/login";
        }
        // 检查用户名密码
        int expiredSeconds = rememberme ? REMEMBER_ME_LOGIN_TICKET : DEFAULT_LOGIN_TICKET;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setMaxAge(expiredSeconds);
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            return "redirect:/index";
        }else{
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket){
        userService.logout(ticket);
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }

}
